package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.di.component.DaggerMemberCenterMainComponent;
import com.kmproject.haifu.mvp.contract.MemberCenterMainContract;
import com.kmproject.haifu.mvp.model.entity.beans.MemberBuyRecordInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberCenterUserInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberFeatureBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.presenter.MemberCenterMainPresenter;
import com.kmproject.haifu.mvp.ui.adapter.MemberCenterMainAdapter;
import com.kmproject.haifu.mvp.ui.widget.CircleImageView;
import com.kmproject.haifu.mvp.ui.widget.RoundCornerImageView;
import com.library.flowlayout.SpaceItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

//import io.github.douglasjunior.androidSimpleTooltip.SimpleTooltip;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/18/2019 15:25
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MemberCenterMainActivity extends BaseActivity<MemberCenterMainPresenter> implements MemberCenterMainContract.View {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.MemberCenterMain_header_img)
    CircleImageView MemberCenterMainHeaderImg;
    @BindView(R.id.MemberCenterMain_Uname_txt)
    TextView MemberCenterMainUnameTxt;
    @BindView(R.id.MemberCenterMain_time_txt)
    TextView MemberCenterMainTimeTxt;
    @BindView(R.id.MemberCenterMain_set_txt)
    TextView MemberCenterMainSetTxt;
    @BindView(R.id.MemberCenterMain_updateMember_img)
    TextView MemberCenterMainUpdateMemberImg;
    @BindView(R.id.MemberCenterMain_bg)
    LinearLayout MemberCenterMainBg;
    @BindView(R.id.MemberCenterMain_fy_kfb_txt)
    TextView MemberCenterMainFyKfbTxt;
    @BindView(R.id.MemberCenterMain_fy_yfb_txt)
    TextView MemberCenterMainFyYfbTxt;
    @BindView(R.id.MemberCenterMain_fy_layout)
    LinearLayout MemberCenterMainFyLayout;
    @BindView(R.id.MemberCenterMain_es_kfb_txt)
    TextView MemberCenterMainEsKfbTxt;
    @BindView(R.id.MemberCenterMain_es_yfb_txt)
    TextView MemberCenterMainEsYfbTxt;
    @BindView(R.id.MemberCenterMain_eswp_layout)
    LinearLayout MemberCenterMainEswpLayout;
    @BindView(R.id.MemberCenterMain_RecyclerView)
    RecyclerView MemberCenterMainRecyclerView;
    @BindView(R.id.MemberCenterMain_dl_img)
    ImageView MemberCenterMainDlImg;

    MemberCenterMainAdapter adapter;
    @BindView(R.id.toolbar_backImg)
    ImageView toolbarBackImg;
    @BindView(R.id.MemberCenterMain_time_img)
    ImageView MemberCenterMainTimeImg;
    @BindView(R.id.MemberCenterMain_bg_img)
    RoundCornerImageView MemberCenterMainBgImg;
    @BindView(R.id.MemberCenterMain_gmjl)
    TextView MemberCenterMainGmjl;

    List<MemberBuyRecordInfoBean> mmemberBuyRecordInfoBeans;
    MemberCenterUserInfoBean memberCenterUserInfoBean;
    MemberCenterUserInfoBean.MemberLevelBean mmemberLevelBean;//管理自动缴费
    @BindView(R.id.MemberCenterMain_dq_layout)
    LinearLayout MemberCenterMainDqLayout;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMemberCenterMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_member_center_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        toolbarTitle.setTextColor(ArmsUtils.getColor(this, R.color.white));
        toolbarBackImg.setImageResource(R.drawable.member_center_main_back_img);
        backRightIcon.setVisibility(View.VISIBLE);
        backRightIcon.setBackgroundResource(R.drawable.member_center_main_gd_img);
        toolbar.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_member_bg));
//        MemberCenterMainBgImg.setmBorderRadius(5);
        initGlide();
        iniUser();
        ArmsUtils.configRecyclerView(MemberCenterMainRecyclerView, new GridLayoutManager(this, 3));
        adapter = new MemberCenterMainAdapter(new ArrayList<>());
        MemberCenterMainRecyclerView.setAdapter(adapter);
        MemberCenterMainRecyclerView.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(10)));
        backRightIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.showRightPopuwindow(MemberCenterMainActivity.this, backRightIcon);

            }
        });
        mPresenter.getMemberLevelByUser();
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    /**
     * 初始化显示用户的信息
     */
    public void iniUser() {
        //用户已经登录
        UserBean userBean = DataHelper.getDeviceData(this, AppConstant.USER_INFO);//获取用户信息
        if (userBean != null) {
            if (userBean.getAvatar() != null && !TextUtils.isEmpty(userBean.getAvatar())) {
                getMglideImage().loadImage(this, ImageConfigImpl.builder().url(userBean.getAvatar()).imageRadius(5)
                        .imageView(MemberCenterMainHeaderImg)
                        .build());
            } else {
                MemberCenterMainHeaderImg.setImageResource(R.drawable.default_headimage);
            }

            MemberCenterMainUnameTxt.setText((userBean.getNickName() == null || TextUtils.isEmpty(userBean.getNickName())) ? "您还没设置昵称" : userBean.getNickName());
        } else {
            MemberCenterMainHeaderImg.setImageResource(R.drawable.default_headimage);
        }
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.MemberCenterMain_gmjl, R.id.MemberCenterMain_time_img, R.id.MemberCenterMain_Uname_txt, R.id.MemberCenterMain_time_txt, R.id.MemberCenterMain_set_txt, R.id.MemberCenterMain_updateMember_img, R.id.MemberCenterMain_bg, R.id.MemberCenterMain_fy_layout, R.id.MemberCenterMain_eswp_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.MemberCenterMain_Uname_txt:
                break;
            case R.id.MemberCenterMain_time_txt:
                if (memberCenterUserInfoBean == null) {
                    return;
                }
                String temMsg = "您当前是"+memberCenterUserInfoBean.getMemberLevel().getLevelName()+"，会员到期时间" +
                            "为 " + memberCenterUserInfoBean.getMemberLevel().getExpiresTime();
//                if (memberCenterUserInfoBean.getMemberLevel().getIsAutoRenew() == 0) {
//                    //自动续费
//                    temMsg = "您当前为自动续费用户，下次扣费时" +
//                            "间为" + memberCenterUserInfoBean.getMemberLevel().getExpiresTime();
//                } else {
//                    //没有自动续费
//                    temMsg = "您当前未开启自动续费，会员到期时间" +
//                            "为" + memberCenterUserInfoBean.getMemberLevel().getExpiresTime();
//
//                }
//                mPresenter.showTipPopuwindow(MemberCenterMainActivity.this, MemberCenterMainTimeTxt, temMsg);

                break;
            case R.id.MemberCenterMain_set_txt:
                if (memberCenterUserInfoBean.getMemberLevel().getIsAutoRenew() == 0) {
                    //未开通自动续费就跳转到升级界面
                    Intent intent = new Intent(this, MemberCenterUpdateLevelActivity.class);
                    intent.putExtra("MemberCenterUserInfoBean", memberCenterUserInfoBean);
                    ArmsUtils.startActivity(intent);
                    return;
                }
                if (mmemberLevelBean == null) {
                    mPresenter.ManageAutomaticRenewal();
                    return;
                }
                mPresenter.showPopuWindowToZDJF(this, MemberCenterMainSetTxt, mmemberLevelBean);
                break;
            case R.id.MemberCenterMain_updateMember_img:
                //去升级
                Intent intent = new Intent(this, MemberCenterUpdateLevelActivity.class);
                intent.putExtra("MemberCenterUserInfoBean", memberCenterUserInfoBean);
                ArmsUtils.startActivityForResult(intent, 1001);
                break;
            case R.id.MemberCenterMain_bg:
                break;
            case R.id.MemberCenterMain_fy_layout:

                break;
            case R.id.MemberCenterMain_eswp_layout:
                break;
            case R.id.MemberCenterMain_time_img:
                if (memberCenterUserInfoBean == null) {
                    return;
                }
//                String temMsg1 = "您当前是"+memberCenterUserInfoBean.getMemberLevel().getLevelName()+"，会员到期\n时间" +
//                        "为 " + memberCenterUserInfoBean.getMemberLevel().getExpiresTime();
//                if (memberCenterUserInfoBean.getMemberLevel().getIsAutoRenew() == 0) {
//                    //自动续费
//                    temMsg1 = "您当前为自动续费用户，下次扣费时" +
//                            "间为" + memberCenterUserInfoBean.getMemberLevel().getExpiresTime();
//                } else {
//                    //没有自动续费
//                    temMsg1 = "您当前未开启自动续费，会员到期时间" +
//                            "为" + memberCenterUserInfoBean.getMemberLevel().getExpiresTime();
//
//                }
//                mPresenter.showTipPopuwindow(MemberCenterMainActivity.this, MemberCenterMainTimeTxt, temMsg1);

                break;
            case R.id.MemberCenterMain_gmjl:
                if (mmemberBuyRecordInfoBeans == null) {
                    mPresenter.getMemberUpgradeRecordList();
                    return;
                }
                mPresenter.showPopuWindowToJFJL(this, MemberCenterMainSetTxt, mmemberBuyRecordInfoBeans);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DefaultAdapter.releaseAllHolder(MemberCenterMainRecyclerView);
    }

    @Override
    public void getMemberLevelByUserSuccess(MemberCenterUserInfoBean memberCenterUserInfoBean) {
        this.memberCenterUserInfoBean = memberCenterUserInfoBean;
       if (getIntent().hasExtra("type")&&getIntent().getStringExtra("type").equals("house_updateMember"))
       {
           Intent intent = new Intent(this, MemberCenterUpdateLevelActivity.class);
           intent.putExtra("MemberCenterUserInfoBean", memberCenterUserInfoBean);
           ArmsUtils.startActivity(intent);
           killMyself();
           return;
       }
        if (memberCenterUserInfoBean.getMemberLevel().getLevelType() != 0) {
            if (memberCenterUserInfoBean.getResidualTimeDay() < 1) {
                showMessage("会员已到期,快去续费吧");
            } else if (memberCenterUserInfoBean.getResidualTimeDay() < 4 && memberCenterUserInfoBean.getResidualTimeDay() > 0) {
                //弹出提示,延迟提示
                MemberCenterMainFyYfbTxt.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        AppUtil.memberCenterMainPopuWindow(MemberCenterMainActivity.this, toolbar, memberCenterUserInfoBean);
                    }
                }, 1000);
            }
        }

        /**
         * 会员类型 0：普通会员 1：中间会员 2：最高级会员
         */
        getMglideImage().loadImage(this, ImageConfigImpl.builder().url(memberCenterUserInfoBean.getMemberLevel().getHeadImage())
                .imageView(MemberCenterMainDlImg)
                .build());
        getMglideImage().loadImage(this, ImageConfigImpl.builder().url(memberCenterUserInfoBean.getMemberLevel().getBackgroundImage()).imageRadius(5).isCenterCrop(true)
                .imageView(MemberCenterMainBgImg)
                .build());

        MemberCenterMainFyYfbTxt.setText(memberCenterUserInfoBean.getHouseRentReleaseCount() + "");
        MemberCenterMainEsYfbTxt.setText(memberCenterUserInfoBean.getSecondHandReleaseCount() + "");
         if (memberCenterUserInfoBean.getHouseTotal() == -1) {
            MemberCenterMainFyKfbTxt.setText("不限");//租房剩余
        } else {
            int temZF=memberCenterUserInfoBean.getHouseTotal() - memberCenterUserInfoBean.getHouseRentReleaseCount();
            MemberCenterMainFyKfbTxt.setText(temZF<0?"0":String.valueOf(temZF));//租房剩余
        }
        if (memberCenterUserInfoBean.getSecondHandTotal() == -1) {
            MemberCenterMainEsKfbTxt.setText("不限");//二手房剩余
        } else {
            int temESF=memberCenterUserInfoBean.getSecondHandTotal() - memberCenterUserInfoBean.getSecondHandReleaseCount();
            MemberCenterMainEsKfbTxt.setText(temESF<0?"0":String.valueOf(temESF));//租房剩余
        }
        if (memberCenterUserInfoBean.getMemberLevel().getIsAutoRenew() == 0) {
            //没开通自动续费
            MemberCenterMainTimeTxt.setText(((memberCenterUserInfoBean.getMemberLevel().getExpiresTime() == null || memberCenterUserInfoBean.getMemberLevel().getExpiresTime().length() < 10) ? "" : memberCenterUserInfoBean.getMemberLevel().getExpiresTime().substring(0, 10)) + "到期");
            //未开通自动续费
            MemberCenterMainSetTxt.setText("开通自动续费");
        } else {
            //开通自动续费
            MemberCenterMainTimeTxt.setText(((memberCenterUserInfoBean.getMemberLevel().getExpiresTime() == null || memberCenterUserInfoBean.getMemberLevel().getExpiresTime().length() < 10) ? "" : memberCenterUserInfoBean.getMemberLevel().getExpiresTime().substring(0, 10)) + "自动续费");
            //开通自动续费
            MemberCenterMainSetTxt.setText("管理自动续费");
        }

        if (memberCenterUserInfoBean.getMemberLevel().getLevelType() == 0) {
            //普通会员
            MemberCenterMainUpdateMemberImg.setText(ArmsUtils.getString(this,R.string.hf_me_qsj));
            MemberCenterMainSetTxt.setVisibility(View.GONE);

            MemberCenterMainDqLayout.setVisibility(View.GONE);
        } else {
            MemberCenterMainUpdateMemberImg.setText(ArmsUtils.getString(this,R.string.hf_me_qxf));
            MemberCenterMainDqLayout.setVisibility(View.VISIBLE);
        }

        mPresenter.getMemberFunctionConfigure(memberCenterUserInfoBean.getMemberLevel().getMemberLevelId());
    }

    @Override
    public void getMemberFunctionConfigureSuccess(List<MemberFeatureBean> memberFeatureBeans) {
        adapter.setNewData(memberFeatureBeans);
    }

    @Override
    public void getMemberUpgradeRecordListSuccess(List<MemberBuyRecordInfoBean> memberBuyRecordInfoBeans) {
        mmemberBuyRecordInfoBeans = memberBuyRecordInfoBeans;
        mPresenter.showPopuWindowToJFJL(this, MemberCenterMainSetTxt, memberBuyRecordInfoBeans);
    }

    @Override
    public ImageLoader getGlideImg() {
        return getMglideImage();
    }

    @Override
    public void manageAutomaticRenewalSuccess(MemberCenterUserInfoBean.MemberLevelBean memberLevelBean) {
        mmemberLevelBean = memberLevelBean;
        mPresenter.showPopuWindowToZDJF(this, MemberCenterMainSetTxt, memberLevelBean);
    }

    @Override
    public void closeAutomaticRenewalSuccess() {
        //关闭成功刷新数据
        mPresenter.getMemberLevelByUser();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK&&data!=null) {
            //购买成功，刷新数据
//            mPresenter.getMemberLevelByUser();
            Intent intent=new Intent();
            if (data.hasExtra("isDialogShow"))
            {
                intent.putExtra("isDialogShow",data.getBooleanExtra("isDialogShow",false));
                AppUtil.isDialogShow = data.getBooleanExtra("isDialogShow",false);
            }else {
                intent.putExtra("isDialogShow",false);
                AppUtil.isDialogShow = false;
            }
            setResult(RESULT_OK,intent);
            killMyself();
        }
    }
}
